package cc.sunni.files.controller;

import cc.sunni.api.controller.files.FileUploaderControllerApi;
import cc.sunni.common.exception.RRException;
import cc.sunni.common.utils.FileUtils;
import cc.sunni.common.utils.R;
import cc.sunni.common.utils.ResultEnum;
import cc.sunni.files.service.UploaderService;
import cc.sunni.pojo.bo.NewAdminBO;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jl
 * @since 2021/2/21 22:39
 */
@RestController
@Slf4j
public class FileUploaderController implements FileUploaderControllerApi {
    @Autowired
    private UploaderService uploaderService;
    @Autowired
    private GridFSBucket gridFSBucket;

    @Override
    public R uploadFace(String userId, MultipartFile file) throws Exception {
        String path;
        if (file != null) {
            // 获得文件上传的名称
            String fileName = file.getOriginalFilename();

            // 判断文件名不能为空
            if (StringUtils.isNotBlank(fileName)) {
                String[] fileNameArr = fileName.split("\\.");
                // 获得后缀
                String suffix = fileNameArr[fileNameArr.length - 1];
                // 判断后缀符合我们的预定义规范
                if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg")) {
                    throw new RRException(ResultEnum.FILE_FORMATTER_FAILD);
                }

                // 执行上传
                path = uploaderService.uploadOSS(file);

            } else {
                throw new RRException(ResultEnum.FILE_UPLOAD_NULL_ERROR);
            }
        } else {
            throw new RRException(ResultEnum.FILE_UPLOAD_NULL_ERROR);
        }
        return R.ok(path);
    }

    @Override
    public R uploadSomeFiles(String userId, MultipartFile[] files) throws Exception {
        // 声明list，用于存放多个图片的地址路径，返回到前端
        List<String> imageUrlList = new ArrayList<>();
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                String path;
                if (file != null) {
                    // 获得文件上传的名称
                    String fileName = file.getOriginalFilename();
                    // 判断文件名不能为空
                    if (StringUtils.isNotBlank(fileName)) {
                        String[] fileNameArr = fileName.split("\\.");
                        // 获得后缀
                        String suffix = fileNameArr[fileNameArr.length - 1];
                        // 判断后缀符合我们的预定义规范
                        if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("jpg") && !suffix.equalsIgnoreCase("jpeg")) {
                            continue;
                        }
                        // 执行上传
                        path = uploaderService.uploadOSS(file);
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }

                if (StrUtil.isNotBlank(path)) {
                    // TODO 放入到imagelist之前，需要对图片做一次审核
                    imageUrlList.add(path);
                }
            }
        }
        return R.ok(imageUrlList);
    }

    @Override
    public R uploadToGridFS(NewAdminBO newAdminBO) throws Exception {
        // 获得图片的base64字符串
        String file64 = newAdminBO.getImg64();
        // 将base64字符串转换为byte数组
        byte[] bytes = new BASE64Decoder().decodeBuffer(file64.trim());
        // 转换为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        // 上传到gridfs中
        ObjectId fileId = gridFSBucket.uploadFromStream(newAdminBO.getUsername() + ".png", inputStream);
        // 获得文件在gridfs中的主键id
        String fileIdStr = fileId.toString();
        return R.ok(fileIdStr);
    }

    @Override
    public void readInGridFS(String faceId, HttpServletRequest request, HttpServletResponse response) {
        // 0. 判断参数
        if (StringUtils.isBlank(faceId) || faceId.equalsIgnoreCase("null")) {
            throw new RRException(ResultEnum.FILE_NOT_EXIST_ERROR);
        }
        // 1. 从gridfs中读取
        GridFSFindIterable gridFSFiles = gridFSBucket.find(Filters.eq("_id", new ObjectId(faceId)));
        GridFSFile gridFS = gridFSFiles.first();
        if (gridFS == null) {
            throw new RRException(ResultEnum.FILE_NOT_EXIST_ERROR);
        }
        String fileName = gridFS.getFilename();
        // 获取文件流，保存文件到临时目录
        File fileTemp = new File(fileName);
        // 创建文件输出流
        try (OutputStream os = new FileOutputStream(fileTemp)) {
            // 下载到服务器或者本地
            gridFSBucket.downloadToStream(new ObjectId(faceId), os);
            // 2. 把人脸图片输出到浏览器
            FileUtils.downloadFileByStream(response, fileTemp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 删除临时文件
            File del = new File(fileTemp.toURI());
            del.delete();
        }
    }

    @Override
    public R readFace64InGridFS(String faceId, HttpServletRequest request, HttpServletResponse response) {
        // 0. 获得gridfs中人脸文件
        GridFSFindIterable gridFSFiles = gridFSBucket.find(Filters.eq("_id", new ObjectId(faceId)));
        GridFSFile gridFS = gridFSFiles.first();
        if (gridFS == null) {
            throw new RRException(ResultEnum.FILE_NOT_EXIST_ERROR);
        }
        String fileName = gridFS.getFilename();
        // 获取文件流，保存文件到临时目录
        File fileTemp = new File(fileName);
        try (OutputStream os = new FileOutputStream(fileTemp)) {
            // 下载到服务器或者本地
            gridFSBucket.downloadToStream(new ObjectId(faceId), os);
            // 1. 转换人脸为base64
            String base64Face = FileUtils.fileToBase64(fileTemp);
            return R.ok(base64Face);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 删除临时文件
            File del = new File(fileTemp.toURI());
            del.delete();
        }
        return R.en(ResultEnum.FILE_NOT_EXIST_ERROR);
    }
}
